package net.ib.mtalk.database.helper;

import java.util.List;
import java.util.Map;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.ContactAccountInfo;
import net.ib.mntalk.protocol.Common.ContactInfo;
import net.ib.mntalk.protocol.Common.UUIDMsg;
import net.ib.mntalk.protocol.Session.AddContactsReq;
import net.ib.mtalk.database.DatabaseContract.BuddyTable;
import net.ib.mtalk.database.DatabaseContract.ContactTable;
import net.ib.mtalk.database.DatabaseContract.GroupTable;
import net.ib.mtalk.database.DatabaseContract.ParticipantsTable;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.sync.ContactComparator;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.ContentProviderOperation;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Groups;
import android.util.Log;

public class ContactDatabaseHelper {
	
	/**
	 * insert
	 * @param Context - context
	 * @param AddContactsReq - addContactsReq
	 * @param map 
	 * @param map_version 
	 */
	public static void insert(Context context, AddContactsReq addContactsReq, Map<String, String> map, Map<String, Integer> map_version){
		ContentValues cv = new ContentValues();
		List<ContactInfo> list = addContactsReq.getContactList();
		long rawcontact_id = 0;
		Map<String, UUIDMsg> buddyListMap = BuddyDatabaseHelper.getBuddyNumber(context);
		
		if(list != null){
			for(ContactInfo info : list){
				cv.clear();
				ContactAccountInfo contactAccountInfo = info.getAccount();
				if(contactAccountInfo.getType() == Common.Phone) {
					cv.put(ContactTable.KEY_CONTACT_NUMBER, contactAccountInfo.getAccountValue());
					cv.put(ContactTable.KEY_CONTACT_IDENTIFIER, contactAccountInfo.getAccountValue().replaceAll("-", "").trim());
					cv.put(ContactTable.KEY_CONTACT_TYPE, contactAccountInfo.getType());
					Cursor cursor = context.getContentResolver().query(Phone.CONTENT_URI, 
							new String[]{Phone.RAW_CONTACT_ID, Phone.NUMBER}, Phone.NUMBER+ "=?", new String[]{contactAccountInfo.getAccountValue()}, Phone.RAW_CONTACT_ID);
					try{
						if(cursor.moveToFirst()){
							rawcontact_id = cursor.getLong(cursor.getColumnIndexOrThrow(Phone.RAW_CONTACT_ID));
							cv.put(ContactTable.KEY_CONTACT_PHONE_ID, rawcontact_id);
							cv.put(ContactTable.KEY_CONTACT_NAME, map.get(String.valueOf(rawcontact_id)));
							cv.put(ContactTable.KEY_CONTACT_VERSION, map_version.get(String.valueOf(rawcontact_id)));
							context.getContentResolver().insert(ContactTable.CONTENT_URI, cv);
						}
						// 버디에 이미 존재할 경우
						if(buddyListMap.containsKey(contactAccountInfo.getAccountValue().replaceAll("-", "").trim())){
							UUIDMsg uuid = (UUIDMsg) buddyListMap.get(contactAccountInfo.getAccountValue().replaceAll("-", "").trim());
							cv.put(ContactTable.KEY_BUDDY_UUID_MSB, GpbSupport.msbOf(uuid));
							cv.put(ContactTable.KEY_BUDDY_UUID_LSB, GpbSupport.lsbOf(uuid));
						}
					} finally{
						cursor.close();
					}
				}
			}
			MTalkLogWriter.i("Contacts Insert Success");
		}
		GlobalPreferences.setContact_Version(ContactComparator.checkContactVersion());
	}	// end insert
	
	/**
	 * Contact Table 에 Data 를 delete 한다.
	 * @param raw_id - CommonDataKinds.Phone.Phone.RAW_CONTACT_ID
	 * @return
	 */
	public static ContentProviderOperation delete(long raw_id) {
		ContentProviderOperation.Builder builder = ContentProviderOperation.newDelete(ContactTable.CONTENT_URI);
		builder.withSelection(ContactTable.KEY_CONTACT_PHONE_ID + "=?", new String[]{String.valueOf(raw_id)});
		return builder.build();
	}
	
	/**
	 * Contact Table 에 Data 를 update 한다.
	 * @param raw_id
	 * @param number
	 * @param version 
	 * @param string 
	 * @return
	 */
	public static ContentProviderOperation updateContact(long raw_id, String key, String value, String version) {
		ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(ContactTable.CONTENT_URI);
		builder.withValue(key, value);
		builder.withValue(ContactTable.KEY_CONTACT_VERSION, version);
		builder.withSelection(ContactTable.KEY_CONTACT_PHONE_ID + "=?", new String[]{String.valueOf(raw_id)});
		return builder.build();
	}
}
						
